package com.tinshow.web.controller.login;

import com.tinshow.config.cookie.CookieUtil;
import com.tinshow.config.utils.*;
import com.tinshow.model.article.Music;
import com.tinshow.model.user.User;
import com.tinshow.service.index.MusicService;
import com.tinshow.service.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;

@RestController
public class LoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private FreeMarkerConfigurer freemarkerConfiguration;

    @RequestMapping(value = "/login_view", method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView loginViewV2(Model model, HttpServletRequest request) {
        Object o = request.getSession().getAttribute("user");
        if (o != null) {
            if (request.getHeader("Referer") != null) {
                return new ModelAndView("redirect:" + request.getHeader("Referer"));
            } else {
                return new ModelAndView("redirect:/");
            }
        }
        model.addAttribute("referer_url", request.getHeader("Referer"));
        model.addAttribute("type", "login");
        return new ModelAndView("/login/login2").addObject(model);
    }

    @RequestMapping(value = "/login_view_v2", method = RequestMethod.GET)
    public ModelAndView loginView(Model model, HttpServletRequest request) {
        Object o = request.getSession().getAttribute("user");
        if (o != null) {
            if (request.getHeader("Referer") != null) {
                return new ModelAndView("redirect:" + request.getHeader("Referer"));
            } else {
                return new ModelAndView("redirect:/");
            }
        }
        model.addAttribute("referer_url", request.getHeader("Referer"));
        model.addAttribute("type", "login");
        return new ModelAndView("/login/login").addObject(model);
    }

    @RequestMapping(value = "/signup_view", method = RequestMethod.GET)
    public ModelAndView signup_view(Model model, HttpServletRequest request) {
        Object o = request.getSession().getAttribute("user");
        if (o != null) {
            if (request.getHeader("Referer") != null) {
                return new ModelAndView("redirect:" + request.getHeader("Referer"));
            } else {
                return new ModelAndView("redirect:/");
            }
        }
        model.addAttribute("referer_url", request.getHeader("Referer"));
        model.addAttribute("type", "signup");
        return new ModelAndView("/login/login2").addObject(model);
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public String loginSubmit(
            Model model,
            @RequestParam(value = "login_email", required = false) String userName,
            @RequestParam(value = "login_pwd", required = false) String password,
            HttpServletRequest request, HttpServletResponse response) {
        User user = new User();
        String pwd = CommonUtils.generatePassword(password);
        user.setEmail(userName);
        user.setPassword(pwd);
        User user1 = userService.selectUser(user);
        StringBuffer sb = null;
        if (user1 != null) {
            try {
                CookieUtil.setSession(user1, request, response);
            } catch (Exception e) {
                e.printStackTrace();
            }
            sb = new StringBuffer();
            sb.append("{\"success\":1}");
            return sb.toString();
        } else {
            sb = new StringBuffer();
            sb.append("{\"success\":0}");
            return sb.toString();
        }

    }

    @RequestMapping(value = "/loginout")
    public ModelAndView loginOut(HttpServletRequest request,
                                 @RequestParam("referUrl") String referUrl) {
        request.getSession().invalidate();
        return new ModelAndView("redirect:" + referUrl);
    }

    @RequestMapping(value = "/signup", method = RequestMethod.POST)
    @ResponseBody
    public String addUserSub(Model model, @RequestParam(value = "rei_pwd", required = false) String password,
                             @RequestParam(value = "rei_email", required = false) String email,
                             @RequestParam(value = "display_name", required = false) String displayName,
                             HttpServletRequest request, HttpServletResponse response) {
        StringBuffer info = new StringBuffer();
        if (StringUtils.isNotEmpty(password) &&
                StringUtils.isNotBlank(displayName) &&
                StringUtils.isNotEmpty(email)) {
            String pwd = CommonUtils.generatePassword(password);
            if (Validator.isEmail(email)) {
                User u1 = new User();
                u1.setEmail(email);
                User u2 = new User();
                u2.setDisplayName(displayName);
                if (userService.selectUser(u2) != null) {
                    return "{\"success\":0,\"msg\":\"displayName_exists\"}";
                } else if (userService.selectUser(u1) != null) {
                    return "{\"success\":0,\"msg\":\"email_exists\"}";
                } else {
                    User user = new User();
                    user.setDisplayName(displayName);
                    user.setEmail(email);
                    user.setPassword(pwd);
                    user.setStatus("verified");
                    String uuid = UUID.randomUUID().toString();
                    user.setValidatorUUID(uuid);
                    String validatorExpire = String.valueOf(DateUtils.addMinutes(new Date(), 30).getTime());
                    user.setValidatorExpire(validatorExpire);
                    /*
                    生成随机数获取随机头像
                     */
                    Random random = new Random();
                    int key = random.nextInt(5) + 1;
                    String imagePath = ImageUtil.getHeadImageMaps(key);
                    user.setProfileImage(imagePath);
                    int userId = userService.insertUser(user);
                    if (userId != 0) {
                        model.addAttribute("name", displayName);
                        model.addAttribute("url", "https://www.tinshow.com/validator/signup?id=" + user.getUserId() + "&e=" + Base64.encode(uuid));
                        doSendMail(model, email, "《听说》邀请您激活账号");
                    }
                    try {
                        CookieUtil.setSession(user, request, response);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return ("{\"success\":\"1\",\"time\":\"" + validatorExpire + "\",\"id\":" + user.getUserId() + "}");
                }
            } else {
                return ("email_error");
            }
        }
        return null;
    }

    @RequestMapping(value = "/validator/signup")
    public ModelAndView validatorSignup(@RequestParam("e") String code,
                                        @RequestParam("id") Integer id) {
        User user1= userService.selectUserById(id);
        long time = new Date().getTime();
        if(Long.parseLong(user1.getValidatorExpire()) < time){

        }
        if (StringUtils.isNotEmpty(code) && id != null) {
            User user = new User();
            user.setUserId(id);
            user.setValidatorUUID(Base64.decode(code));
            user.setStatus("active");
            userService.updateUser(user);
            System.out.println("success");
        }
        return null;
    }

    @RequestMapping("/signup/success/{userId}/{timestamp}")
    public ModelAndView signupSuccess(Model model, @PathVariable Integer userId, @PathVariable String timestamp) {
        User user = userService.selectUserById(userId);
        if ("active".equals(user.getStatus())){
            model.addAttribute("user_active", "请勿重复提交！");
            return new ModelAndView("login/user_active").addObject(model);
        }
        long time = new Date().getTime();
        if (time < Long.parseLong(user.getValidatorExpire())) {
            String emailTxt = user.getEmail().split("@")[1].replaceAll(".com", "");
            switch (emailTxt) {
                case "163":
                    model.addAttribute("email", MailUtil.NETEASY_163_ADDRESS);
                    break;
                case "126":
                    model.addAttribute("email", MailUtil.NETEASY_126_ADDRESS);
                    break;
                case "qq":
                    model.addAttribute("email", MailUtil.QQ_ADDRESS);
                    break;
                case "outlook":
                    model.addAttribute("email", MailUtil.OUTLOOK_ADDRESS);
                    break;
                case "gmail":
                    model.addAttribute("email", MailUtil.GMAIL_ADDRESS);
                    break;
                case "sina":
                    model.addAttribute("email", MailUtil.SINA_ADDRESS);
                    break;
                case "aliyun":
                    model.addAttribute("email", MailUtil.ALIYUN_ADDRESS);
                    break;
                default:
                    model.addAttribute("email", "mail." + emailTxt + ".com");
                    break;

            }
            model.addAttribute("userId",userId);
            return new ModelAndView("login/signup_success").addObject(model);
        }
        return null;
    }

    public void doSendMail(Model model, String toAddress, String subject) {
        try {
            MailSenderInfo mailInfo = new MailSenderInfo();
            mailInfo.setToAddress(toAddress);
            mailInfo.setSubject(subject);
            String context = FreeMarkerTemplateUtils.processTemplateIntoString(
                    freemarkerConfiguration.getConfiguration().getTemplate("/login/signup_validator.ftl"), model);
            mailInfo.setContent(context);
            MailUtil.sendHtmlMail(mailInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
